package cn.touna.jss.common.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 公共方法
 */
public class Common {

    public static Map<String,DecimalFormat> decimalFormatMap = new HashMap<>();
    public synchronized static String format(double value,String format){
        DecimalFormat decimalFormat = decimalFormatMap.get(format);
        if(decimalFormat == null){
            decimalFormat = new DecimalFormat(format);
            decimalFormatMap.put(format,decimalFormat);
        }
        return decimalFormat.format(value);
    }

    public static void jsonPathCopy(JSONObject src,JSONObject dest,String srcPath,String destPath){
        JSONPath.set(dest,destPath,JSONPath.eval(src,srcPath));
    }

    public static void jsonFieldCopy(JSONObject src,JSONObject dest,String srcField,String destField){
        dest.put(destField, ifNull(src.getString(srcField),""));
    }

    public static void jsonFieldCopy(JSONObject src,JSONObject dest,String field){
        dest.put(field, ifNull(src.getString(field),""));
    }

    public static String ifNull(String value, String defaultValue){
        if(value == null)
            return defaultValue;
        return value;
    }

    /**
     * map格式的字符串转json对象<br/>
     * 用来修补hbase存储json字符串异常的问题
     * @param dataStr
     * @return
     */
    public static JSONObject mapStr2Json(String dataStr){
        JSONObject result = new JSONObject();
        if(dataStr.startsWith("{") && dataStr.endsWith("}")){
            dataStr = dataStr.substring(1,dataStr.length() -1);
            String[] arr1 = dataStr.split("=");
            String key = null;
            String value;
            for(int i =0;i<arr1.length;i++){
                if(i == 0){
                    key = arr1[i];
                }else{
                    String str = arr1[i];
                    int ind = str.lastIndexOf(",");
                    if(ind == -1){
                        result.put(key.trim(),getJson(str));
                    }else{
                        value = str.substring(0,ind);
                        result.put(key.trim(),getJson(value));
                        key = str.substring(ind + 1);
                    }
                }
            }
        }
        return result;
    }

    private static Object getJson(String str){
        if(str.startsWith("[") && str.endsWith("]")){
            return JSONArray.parseArray(str);
        }else if(str.startsWith("{")&&str.endsWith("}"))
            return JSONObject.parseObject(str);
        return str;
    }

    /**
     * 编码
     *
     * @param bstr
     * @return String
     */
    public static String encode(byte[] bstr) {
        return Base64.encode(bstr);
    }

    /* Signature algorithm using HMAC-SHA1 */
    public static String hmacSHA1(String key, String text) throws InvalidKeyException, NoSuchAlgorithmException {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(key.getBytes(), "HmacSHA1"));
        return encode(mac.doFinal(text.getBytes()));
    }

    /* Assemble query string */
    public static String makeQueryString(Map<String, String> args, String charset) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : args.entrySet()) {
            String value = charset == null ? entry.getValue() : URLEncoder.encode(entry.getValue(), charset);
            sb.append(entry.getKey()).append("=").append(value).append("&");
        }
        if (sb.length() > 0)
            sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static String streamToString(InputStream inputStream) {
        StringBuffer stringBuffer = null;
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            stringBuffer = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
        } catch (IOException e) {
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    return null;
                }
            }
        }
        return stringBuffer.toString();
    }
}
